var $ = getApp(), methods = require("../methods.js");
Page(Object.assign({}, methods, {
	data: {
		isload: 0,
		address: [],
		usescore: 0,
		dkmoney:0,
		totalprice: '0.00',
		couponvisible:false,
		bid:0,
		nowbid:0,
		needaddress:1,
		linkman:'',
		tel:'',
		pstimeDialogShow:false,
		pstimeIndex:-1,
	},
	_onLoad: function () {
		var that = this;
		//获取产品信息
		$.get('lipin/prodh', { dhcode: that.options.dhcode }, function (res) {
			if (res.status == 0) {
				$.alert(res.msg,function(){
					$.goback();
				})
				return;
			}
			res.isload = 1
			that.setData(res);
			that.calculatePrice();
			if(res.needLocation==1){
				wx.getLocation({
					type: 'gcj02',
					success:function(res){
						var latitude = res.latitude
						var longitude = res.longitude
						that.setData({latitude:latitude,longitude:longitude});
						var allbuydata = that.data.allbuydata
						for(var i in allbuydata){
							var freightList = allbuydata[i].freightList;
							for(var j in freightList){
								if(freightList[j].pstype == 1){
									var storedata = freightList[j].storedata
									if(storedata){
										for(var x in storedata){
											if(latitude && longitude && storedata[x].latitude && storedata[x].longitude){
												var juli = that.getDistance(latitude,longitude,storedata[x].latitude,storedata[x].longitude);
												storedata[x].juli = juli;
											}
										}
										storedata.sort(function(a,b){
											return a["juli"]-b["juli"];
										});
										for(var x in storedata){
											if(storedata[x].juli){
												storedata[x].juli = storedata[x].juli + '千米';
											}
										}
										allbuydata[i].freightList[j].storedata = storedata;
									}
								}
							}
						}
						that.setData({allbuydata:allbuydata});
					}
				});
			}
		});
	},
	//积分抵扣
	scoredk: function (e) {
		var usescore = e.detail.value[0];
		if (!usescore) usescore = 0
		this.setData({ usescore: usescore });
		this.calculatePrice();

	},
	inputLinkman:function(e){
		this.setData({ linkman: e.detail.value });
	},
	inputTel:function(e){
		this.setData({ tel: e.detail.value });
	},
	inputBeizhu: function (e) {
		var that = this;
		var allbuydata = that.data.allbuydata
		var bid = e.currentTarget.dataset.bid
		allbuydata[bid].message = e.detail.value
		this.setData({ allbuydata: allbuydata });
	},
	inputfield1: function (e) {
		var that = this;
		var allbuydata = that.data.allbuydata
		var bid = e.currentTarget.dataset.bid
		allbuydata[bid].field1 = e.detail.value
		this.setData({ allbuydata: allbuydata });
	},
	inputfield2: function (e) {
		var that = this;
		var allbuydata = that.data.allbuydata
		var bid = e.currentTarget.dataset.bid
		allbuydata[bid].field2 = e.detail.value
		this.setData({ allbuydata: allbuydata });
	},
	inputfield3: function (e) {
		var that = this;
		var allbuydata = that.data.allbuydata
		var bid = e.currentTarget.dataset.bid
		allbuydata[bid].field3 = e.detail.value
		this.setData({ allbuydata: allbuydata });
	},
	inputfield4: function (e) {
		var that = this;
		var allbuydata = that.data.allbuydata
		var bid = e.currentTarget.dataset.bid
		allbuydata[bid].field4 = e.detail.value
		this.setData({ allbuydata: allbuydata });
	},
	inputfield5: function (e) {
		var that = this;
		var allbuydata = that.data.allbuydata
		var bid = e.currentTarget.dataset.bid
		allbuydata[bid].field5 = e.detail.value
		this.setData({ allbuydata: allbuydata });
	},
	//选择收货地址
	chooseAddress: function () {
		$.goto('/pages/address/address?fromPage=buy');
	},
	//计算价格
	calculatePrice: function () {
		var that = this;
		var address = that.data.address
		var allbuydata = that.data.allbuydata

		var alltotalprice = 0;
		var allfreightprice = 0;
		var needaddress = 0;
		for(var k in allbuydata){
			var goodsprice = parseFloat(allbuydata[k].goodsprice);
			var disprice = parseFloat(allbuydata[k].disprice);
			var couponmoney = parseFloat(allbuydata[k].couponmoney)	//-优惠券抵扣 
			//算运费
			var freightdata = allbuydata[k].freightList[allbuydata[k].freightkey];
			var freightprice = 0;
			if(freightdata.pstype!=1 && freightdata.pstype!=3){
				needaddress = 1;
			}
			console.log(needaddress)
			if(freightdata.pstype==0){
				var ftype = freightdata.type;
				var freeset = freightdata.freeset
				var free_price = parseFloat(freightdata.free_price);
				var pricedata = freightdata.pricedata;
				pricedata = JSON.parse(pricedata)
				for (var i = 0; i < pricedata.length; i++) {
					var thisdata = pricedata[i];
					var region = thisdata['region'];
					var regionlist = region.split('];');
					for (var j = 0; j < regionlist.length; j++) {
						var regiondata = regionlist[j].split('[');
						if (regiondata[0] == '全国(默认运费)' || (regiondata[0] == address['province'] && (regiondata[1] == '全部地区' || $.inArray(address['city'], regiondata[1].split(','))))) {
							if(freeset==1 && free_price <=goodsprice){
								freightprice = 0;
							}else{
								if(ftype==1){ //按重量
									freightprice = parseFloat(thisdata.fristprice);   //首重价格
									if (allbuydata[k].weight - parseFloat(thisdata.fristweight) > 0) {
										freightprice += Math.ceil((allbuydata[k].weight - parseFloat(thisdata.fristweight)) / parseFloat(thisdata.secondweight)) * parseFloat(thisdata.secondprice)  //+续重价格
									}
								}else{ //按件数
									freightprice = parseFloat(thisdata.fristprice);   //首件价格
									if (allbuydata[k].goodsnum - parseFloat(thisdata.fristweight) > 0) {
										freightprice += Math.ceil((allbuydata[k].goodsnum - parseFloat(thisdata.fristweight)) / parseFloat(thisdata.secondweight)) * parseFloat(thisdata.secondprice)  //+续件价格
									}
								}
							}
						}
					}
				}
			}else if(freightdata.pstype==1){//自提
				allbuydata[k].storedata = freightdata.storedata;
			}else if(freightdata.pstype==2){ //同城配送
				var freeset = freightdata.freeset
				var free_price = parseFloat(freightdata.free_price);
				freightprice = freightdata.freightprice
				if(freeset==1 && free_price <= goodsprice){
					freightprice = 0;
				}
			}
			if(allbuydata[k].coupontype==4){
				freightprice = 0;
				couponmoney = 0;
			}
			var totalprice = goodsprice - disprice - couponmoney;
			if(totalprice < 0) totalprice = 0;  //优惠券不抵扣运费
			totalprice = totalprice	+ freightprice;

			allbuydata[k].freightprice = freightprice.toFixed(2)
			allbuydata[k].totalprice = totalprice.toFixed(2)

			alltotalprice += totalprice;
			allfreightprice += freightprice;
		}
		that.setData({needaddress:needaddress})
		if(that.data.usescore){
			var dkmoney = parseFloat(that.data.userinfo.dkmoney);			//-积分抵扣
		} else {
			var dkmoney = 0;
		}
		alltotalprice = alltotalprice - dkmoney;
		if (alltotalprice < 0) alltotalprice = 0;
		if(that.data.scorebdkyf=='1' && dkmoney > 0 && alltotalprice < allfreightprice) alltotalprice = allfreightprice; //积分不抵扣运费
		alltotalprice = alltotalprice.toFixed(2)
		that.setData({alltotalprice: alltotalprice,allbuydata:allbuydata})
	},
	chooseFreight:function(e){
		var that = this;
		var allbuydata = that.data.allbuydata
		var bid = e.currentTarget.dataset.bid
		console.log(bid)
		console.log(allbuydata)
		var freightList = allbuydata[bid].freightList
		var itemlist = [];
		for(var i=0;i<freightList.length;i++){
			itemlist.push(freightList[i].name);
		}
		wx.showActionSheet({
			itemList:itemlist,
			success:function(res) {
				allbuydata[bid].freightkey = res.tapIndex
				that.setData({ allbuydata: allbuydata });
				that.calculatePrice();
			}
		});
	},
	choosePstime:function(e){
		var that = this;
		var allbuydata = that.data.allbuydata
		var bid = e.currentTarget.dataset.bid
		var freightkey = allbuydata[bid].freightkey;
		var freightList = allbuydata[bid].freightList;
		var freight = freightList[freightkey]
		var pstimeArr = freightList[freightkey].pstimeArr
		var itemlist = [];
		for(var i=0;i<pstimeArr.length;i++){
			itemlist.push(pstimeArr[i].title);
		}
		if(itemlist.length == 0){
			$.alert('当前没有可选'+(freightList[freightkey].pstype==1?'取货':'配送')+'时间段');
			return;
		}
		if(itemlist.length > 6){
			that.setData({nowbid:bid,pstimeDialogShow:true,pstimeIndex:-1})
		}else{
			wx.showActionSheet({
				itemList:itemlist,
				success:function(res) {
					var choosepstime = pstimeArr[res.tapIndex]
					allbuydata[bid].pstimetext = choosepstime.title;
					allbuydata[bid].freight_time = choosepstime.value;
					that.setData({ allbuydata: allbuydata});
				}
			});
		}
	},
	pstimeRadioChange:function(e){
		this.setData({pstimeIndex:e.detail.value})
	},
	pstimeSelectConfirm:function(){
		var that = this;
		var allbuydata = that.data.allbuydata
		var pstimeIndex = that.data.pstimeIndex
		var nowbid = that.data.nowbid
		var freightkey = allbuydata[nowbid].freightkey;
		var freightList = allbuydata[nowbid].freightList;
		var freight = freightList[freightkey]
		var pstimeArr = freightList[freightkey].pstimeArr
		if(pstimeIndex == -1){
			$.error('请选择'+(freightList[freightkey].pstype==1?'取货':'配送')+'时间');return;
		}
		var choosepstime = pstimeArr[pstimeIndex]
		allbuydata[nowbid].pstimetext = choosepstime.title;
		allbuydata[nowbid].freight_time = choosepstime.value;
		that.setData({ allbuydata: allbuydata});
		that.setData({pstimeDialogShow:false})
	},
	hidePstimeDialog:function(){
		this.setData({pstimeDialogShow:false})
	},
	chooseCoupon:function(e){
		var that = this;
		var allbuydata = that.data.allbuydata
		var bid = e.currentTarget.dataset.bid;
		var couponrid = e.currentTarget.dataset.id;
		var couponkey = e.currentTarget.dataset.key;
		if(couponrid == allbuydata[bid].couponrid){
			allbuydata[bid].couponkey = 0
			allbuydata[bid].couponrid = 0
			allbuydata[bid].coupontype = 1
			allbuydata[bid].couponmoney = 0
			this.setData({allbuydata:allbuydata,couponvisible:false});
		}else{
			var couponList = allbuydata[bid].couponList;
			var couponmoney = couponList[couponkey]['money']
			var coupontype = couponList[couponkey]['type']
			allbuydata[bid].couponkey = couponkey
			allbuydata[bid].couponrid = couponrid
			allbuydata[bid].coupontype = coupontype
			allbuydata[bid].couponmoney = couponmoney
			this.setData({allbuydata:allbuydata,couponvisible:false});
		}
		this.calculatePrice();
	},
	choosestore:function(e){
		var that = this;
		var allbuydata = that.data.allbuydata
		var bid = e.currentTarget.dataset.bid
		allbuydata[bid].storeid = e.detail.value
		console.log(allbuydata[bid].storedata)
		var storename = '';
		var latitude = '';
		var longitude = '';
		for(var i in allbuydata[bid].storedata){
			if(allbuydata[bid].storedata[i].id == allbuydata[bid].storeid){
				storename = allbuydata[bid].storedata[i].name;
				latitude = allbuydata[bid].storedata[i].latitude;
				longitude = allbuydata[bid].storedata[i].longitude;
			}
		}
		console.log(storename);
		allbuydata[bid].storename = storename
		allbuydata[bid].latitude = latitude
		allbuydata[bid].longitude = longitude
		this.setData({allbuydata:allbuydata})
	},
	//提交并支付
	topay: function () {
		var that = this;
		var needaddress = that.data.needaddress
		var addressid = this.data.address.id
		var linkman = this.data.linkman;
		var tel = this.data.tel;
		var usescore = this.data.usescore;
		var frompage = that.options.frompage ? that.options.frompage : ''
		var allbuydata = that.data.allbuydata
		if(needaddress==0) addressid = 0;
		if (needaddress==1 && addressid == undefined) {
			$.error('请选择收货地址'); return;
		}//else{
		//	if(linkman=='' || tel==''){
		//		$.error('请输入您的姓名和手机号'); return;
		//	}
		//}
		var buydata = [];
		for(var i in allbuydata){
			if(allbuydata[i].freightList[allbuydata[i].freightkey].pstimeset==1 && allbuydata[i].freight_time==''){
				$.error('请选择'+(allbuydata[i].freightList[allbuydata[i].freightkey].pstype==1?'取货':'配送')+'时间'); return;
			}
			if(allbuydata[i].freightList[allbuydata[i].freightkey].pstype==1 && allbuydata[i].storeid==''){
				$.error('请选择取货地点'); return;
			}
			buydata.push({bid:allbuydata[i].bid,prodata:allbuydata[i].prodatastr,couponrid:allbuydata[i].couponrid,freightid:allbuydata[i].freightList[allbuydata[i].freightkey].id,freight_time:allbuydata[i].freight_time,storeid:allbuydata[i].storeid,message:allbuydata[i].message,field1:allbuydata[i].field1,field2:allbuydata[i].field2,field3:allbuydata[i].field3,field4:allbuydata[i].field4,field5:allbuydata[i].field5})
		}
		$.post('lipin/createOrder',{dhcode: that.options.dhcode,frompage:frompage,buydata:buydata,addressid:addressid,linkman:linkman,tel:tel,usescore:usescore}, function (res) {
			if (res.status == 0) {
				$.error(res.msg);
				return;
			}else{
				$.alert(res.msg,function(){
					$.goto('/pages/my/usercenter');
				});
			}
		},'提交中')
	},
	showCouponList:function(e){
		this.setData({couponvisible:true,bid:e.currentTarget.dataset.bid})
	},
	handleClickMask:function(){
		this.setData({couponvisible:false})
	},
}));